package com.huatech.core.support.redis;
import java.util.List;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;

public class RedisUtil {

	static JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
	
	public static Jedis getResource(){
		return jedisPool.getResource();
	}
	
	public static void set(byte[] key, byte[] value, int seconds){
		Jedis jedis = getResource();
		try{
			jedis.set(key, value);
			if(seconds > 0){
				jedis.expire(key, seconds);
			}
		}finally{
			jedis.close();
		}	
	}
	
	public static byte[] get(byte[] key){
		Jedis jedis = getResource();
		try{
			return jedis.get(key);
		}finally{
			jedis.close();
		}
	}
	
	public static void del(byte[] key){
		Jedis jedis = getResource();
		try{
			jedis.del(key);
		}finally{
			jedis.close();
		}
	}
	
	public static List<String> keys(String prefix){
        Jedis jedis = getResource();
        ScanParams scanParams = new ScanParams();
        scanParams.match(prefix + "*");
        scanParams.count(10000);
        try{
	        ScanResult<String> scan = jedis.scan("0", scanParams);
	        return scan.getResult();
        }finally{
        	jedis.close();
        }
	}
	
	
	/******************** hash 操作 start ********************/
	
	public static byte[] hget(byte[] key, byte[] field){
		Jedis jedis = getResource();
		try{
			return jedis.hget(key, field);
		}finally{
			jedis.close();
		}
	}
	
	public static void hset(byte[] key, byte[] field, byte[] value){
		Jedis jedis = getResource();
		try{
			jedis.hset(key, field, value);
		}finally{
			jedis.close();
		}
	}
	
	public static void hdel(byte[] key, byte[] field){
		Jedis jedis = getResource();
		try{
			jedis.hdel(key, field);
		}finally{
			jedis.close();
		}
	}
	
	public static Long hlen(byte[] key){
		Jedis jedis = getResource();
		try{
			return jedis.hlen(key);
		}finally{
			jedis.close();
		}
	}
	public static Set<byte[]> hkeys(byte[] key){
		Jedis jedis = getResource();
		try{
			return jedis.hkeys(key);
		}finally{
			jedis.close();
		}
	}
	
	public static List<byte[]> hvals(byte[] key){
		Jedis jedis = getResource();
		try{
			return jedis.hvals(key);
		}finally{
			jedis.close();
		}
	}
	/******************** hash 操作 end ********************/
	
}